<template>
  <div class="book-carousel" :style="{height: height}" @mouseleave="autoPlayer" @mouseover="stopAutoPlayer()">
    <div class="img-group" :style="{transform: `translateX(${translateX})`}">
      <img
        :style="{height: height}"
        v-for="(item, index) in carouselList"
        :key="index"
        :src="item.img"
      >
    </div>
    <div class="change-bar">
      <router-link
        v-for="(item, index) in carouselList"
        :to="{path: item.path}"
        class="change-item"
        :class="changeActive === index ? 'active' : ''"
        @mouseover.native="changeImg(index)"
        :key="index">
        {{ item.title }}
      </router-link>
    </div>
  </div>
</template>

<script>
export default {
  name: 'bookCarousel',
  data () {
    return {
      player: undefined,
      changeActive: 0
    }
  },
  props: {
    height: {
      type: String,
      default: '200px'
    },
    carouselList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    translateX () {
      return `${this.changeActive * -1 * 100}%`
    }
  },
  methods: {
    // 切换轮播
    changeImg (index) {
      this.changeActive = index
    },
    // 自动播放
    autoPlayer () {
      this.player = setInterval(() => {
        if (this.changeActive < this.carouselList.length - 1) {
          this.changeActive++
        } else {
          this.changeActive = 0
        }
      }, 3000)
    },
    // 停止自动播放
    stopAutoPlayer (index) {
      clearInterval(this.player)
    }
  },
  created () {
    this.autoPlayer()
  }
}
</script>

<style lang="scss" scoped>
 .book-carousel {
   position: relative;
   width: 100%;
   background: #123456;
   overflow: hidden;
   z-index: 1;
   > .img-group {
     display: flex;
     flex-direction: row;
     transform: translateX(0%);
     transition: all 0.5s;
     img {
       width: 100%;
       margin: 0;
       padding: 0;
     }
   }
   .change-bar {
     position: absolute;
     display: flex;
     flex-direction: column;
     top: 20px;
     right: 20px;
     .change-item {
       background: rgba(255, 255, 255, 0.5);
       padding: 0 15px;
       line-height: 30px;
       text-decoration: none;
       color: #000000;
       font-size: 12px;
       margin-bottom: 2px;
       &:hover, &.active {
         background: rgba(255, 255, 255, 0.8);
       }
     }
   }
 }
</style>
